#include "app.h"

App::App()
{
    popularPagesSize = 20;
    oneHostOneUser = true;

    debugMode = false;

    parser = new LogFileParser;
    extractor = new SessionExtractor;
    basket = new Basket;
    //apriori = new Apriori;        // this algorytm rather never gonna be in use, computation are too complex
    tree = new FPTree;
}

App::~App()
{
    delete tree; tree = 0;
    delete basket; basket = 0;
    delete extractor; extractor = 0;
    delete parser; parser = 0;
}

void App::setFilename(QString filename)
{
    this->filename = filename;
}

void App::setPopularPagesSize(int size)
{
    this->popularPagesSize = size;
}

void App::setSessionDuration(int sessionDuration)
{
    this->sessionDuration = sessionDuration;
}

void App::setOneHostOneUser(bool value)
{
    this->oneHostOneUser = value;
}

void App::run()
{
    qDebug() << QDateTime::currentDateTime();
    // Step 1 -- read and parse file
    parser->setFilename(this->filename);
    parser->openStream();
    parser->removeJunks();
    //parser->getRequests();

    // Step 2 -- extract data
    extractor->setRequests(parser->getRequests());
    extractor->setSessionTime(sessionDuration);

    // Find most popular pages and create basket
    extractor->findMostPopularPages();
    QList<QPair<QString,int> *> *mostPopularPages = extractor->getMostPopularPages();


    for(int i = 0; i < this->popularPagesSize; ++i)
        basket->addPage(mostPopularPages->at(i)->first);

    //basket->debug();

    // Below this line, requests are unnecessery
    //  Releasing memory...
    //    ....

    // Find all unique hosts in file.
    extractor->findAllHosts();          // Critical! This method has to be called before findAllSessions

    // And finally find all sessions
    extractor->findAllSessions();

    extractor->compressSessions(50);

    // Copy pointer to sessions and put them all to basket
    sessions = extractor->getSessions();
    for(int i = 0; i < sessions->size(); ++i)
        basket->addSession(sessions->at(i));

    //basket->debug();
    //extractor->debug();

    basket->saveBasketAsArff("test.arff");

    // In this place, app has completed basked so all kind of parsing and extraction of log file has been done.
    //   Now is time for data mining. But first release all not using memory.

    // Releasing memory...

    // Let's start FPTree algorithm
    //   Firstly insert all pages to the treeeee
    //for(int i = 0; i < sessions->size(); ++i)
    //for(int i = 0; i < 10; ++i)
    //{
    //    QStringList *lista = &(sessions->at(i)->getPages());
    //    tree->addPages(lista);
        //qDebug() << "dodalem" << *lista;
    //}

    qDebug() << QDateTime::currentDateTime();
    qDebug() << "==============================";
    //tree->showTree();
}

